package com.jysz.certificate.web.filter;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.StrutsStatics;

import com.jysz.certificate.action.AbstractBaseAction;
import com.jysz.certificate.persistence.model.system.User;
import com.jysz.webcore.ssh.annotation.PermissionPoint;
import com.jysz.webcore.ssh.web.struts2.GenericAction;
import com.jysz.webcore.ssh.web.struts2.SshAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class PermissionInterceptor extends AbstractInterceptor {
	
	private static final long serialVersionUID = 1L;
	final static String EMPTY_OPER_CODE = "empty_oper_code";
	

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {

		ActionContext actionContext = invocation.getInvocationContext();
		HttpServletRequest httpServletRequest= (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
		AbstractBaseAction baseAction = (AbstractBaseAction) invocation.getAction();
		User user = (User) httpServletRequest.getSession(false).getAttribute(GenericAction.LOGIN_SESSION);
		
		if(user == null) {
			return invocation.invoke();
		} else {
			
			String operCode = EMPTY_OPER_CODE;
			String actionName = invocation.getProxy().getActionName();
			Method method = baseAction.getClass().getMethod(actionName);
			PermissionPoint pp = method.getAnnotation(PermissionPoint.class);
			
			if(pp != null && StringUtils.isNotBlank(pp.point())) {
				operCode = pp.point();
			}
			
			if(operCode != null && (EMPTY_OPER_CODE.equals(operCode) || baseAction.hasOper(operCode))) { //pass
				return invocation.invoke();
			} else { // not pass
				if(actionName.startsWith("ajaxJson")) { //ajax请求
					baseAction.setJsonText("{timeout: false, flag: false, msg: '权限不足', data: null}");
					return SshAction.JSON_PAGE;
				} else { //html请求
					baseAction.setFailPopMessage("权限不足");
					return SshAction.SHOW_MSG_PAGE;
				}
			}
		}
	}
}

